import { body } from "express-validator";
import { User } from "../../model/index.js";
import validator from "./errorBack.js";
// 用户注册参数验证
export const registerValidator = validator([
  body("username")
    .notEmpty()
    .withMessage("用户名不能为空")
    .isLength({ min: 2, max: 10 })
    .withMessage("用户名长度必须在2-10之间"),
  body("email")
    .custom(async (value, { req }) => {
      if (!value) {
        throw new Error("邮箱不能为空");
      }
      const existingUser = await User.findOne({ email: req.body.email });
      if (existingUser) {
        throw new Error("邮箱已被注册");
      }
      return true;
    })
    .bail(),
  body("phone")
    .isMobilePhone()
    .withMessage("请输入正确的手机号格式")
    .custom(async (value, { req }) => {
      if (!value) {
        throw new Error("手机号不能为空");
      }
      const existingUser = await User.findOne({ phone: req.body.phone });
      if (existingUser) {
        throw new Error("手机号已被注册");
      }
      return true;
    })
    .bail(),
  body("password").isLength({ min: 6 }).withMessage("密码长度不能小于6位"),
]);

// 用户登陆参数验证
export const loginValidator = validator([
  body("email")
    .isEmail()
    .withMessage("请输入正确的邮箱格式")
    .custom(async (value) => {
      const user = await User.findOne({ email: value });
      if (!user) {
        throw new Error("邮箱未注册");
      }
    })
    .bail(),
  body("password")
    .notEmpty()
    .withMessage("密码不能为空")
    .custom(async (value) => {
      const user = await User.findOne({ password: value });
      if (!user) {
        throw new Error("密码错误");
      }
    })
    .bail(),
]);

// 编辑用户
export const updateValidator = validator([
  body("username")
    .custom(async (value) => {
      const user = await User.findOne({ username: value });
      if (user) {
        throw new Error("用户名已被注册");
      }
    })
    .bail(),
]);

